package com.iot.comprehensive.face.controller;

import com.iot.comprehensive.face.model.Account;
import com.iot.comprehensive.face.service.AccountService;
import com.iot.comprehensive.face.utils.Jwt;
import com.iot.comprehensive.face.utils.Result;
import com.iot.comprehensive.face.utils.ResultCode;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.apache.commons.codec.digest.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 朱泽玉
 * @Create 2021/6/26 13:46
 * @Description
 * @Modified By:
 */
@RestController
@RequestMapping("/account")
@Api(tags = "账号操作", protocols = "http,https")
@ApiResponses({
        @ApiResponse(code = 200, message = "登录成功"),
        @ApiResponse(code = 300, message = "出现错误"),
        @ApiResponse(code = 301, message = "无权限(未认证)")
})
public class AccountController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private Jwt jwt;

    /**
     * 用户登录
     *
     * @param mobile   手机号码
     * @param password 密码
     * @return token数据
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    @ApiOperation(value = "登录", notes = "登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号", required = true, example = "15635735200"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, example = "123456")
    })
    public Result login(
            @RequestParam("mobile") String mobile,
            @RequestParam("password") String password) {
        try {
            Account account = accountService.findByMobile(mobile);
            //密码错误
            if (account == null || !DigestUtils.sha256Hex(password).equals(account.getPassword())) {
                return new Result(ResultCode.FAIL, "用户名不存在或密码错误");
            }
            if (account.getIsCertified() == 0) {
                return new Result(ResultCode.UN_AUTHORISE, "未进行认证");
            }
            //密码正确
            //赋值token数据
            Map<String, Object> map = new HashMap<>();
            map.put("mobile", account.getMobile());
            map.put("password", password);
            //创建token对象
            String token = jwt.create(Long.toString(account.getId()), map);
            return new Result(ResultCode.SUCCESS, token);

        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR, e);
        }
    }

    /**
     * 用户注册
     *
     * @param mobile   用户手机号
     * @param password 密码
     * @return 注册信息
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ApiOperation(value = "注册", notes = "注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号", required = true, example = "15635735200"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, example = "123456")
    })
    public Result register(
            @RequestParam("mobile") String mobile,
            @RequestParam("password") String password) {
        try {
            // 1.查看该手机号是否已经被注册
            Account account = accountService.findByMobile(mobile);
            // 2（a）没有被注册的话进行注册
            if (account == null) {
                accountService.add(mobile, password);
                //创建token对象
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("mobile", mobile);
                map.put("password", password);
                Account account1 = accountService.findByMobile(mobile);
                String token = jwt.create(Long.toString(account1.getId()), map);
                //返回
                return new Result(ResultCode.SUCCESS, token);
            }
            // 2（b）已经被注册话返回
            else {
                return new Result(ResultCode.FAIL, "手机号已被注册");
            }
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR, e);
        }
    }


    /**
     * 用户信息修改
     *
     * @param mobile   手机号码
     * @param password 密码
     * @return 修改后的信息
     */
    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    @ApiOperation(value = "更新密码", notes = "更新密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号", required = true, example = "15635735200"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, example = "123456")
    })
    public Result update(
            @RequestParam("mobile") String mobile,
            @RequestParam("password") String password,
            HttpServletRequest request) {
        try {
            // 1、获取返回的token
            Claims token = jwt.token(request);
            // 4、获取token中的id值
            if (token == null) {
                return new Result(ResultCode.FAIL, "请重新登录后再次尝试");
            }
            Long id = Long.valueOf(token.getId());
            // 5、进行修改
            Account account = accountService.findById(id);
            account.setMobile(mobile);
            account.setPassword(password);
            account.setId(id);
            accountService.update(account);
            return new Result(ResultCode.SUCCESS);
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR, e);
        }
    }


    /**
     * 根据header获取身份
     * @param request header
     * @return 身份
     */
    @RequestMapping(value = "/identity", method = RequestMethod.GET)
    @ApiOperation(value = "获取身份", notes = "获取身份(header中的token定位)")
    public Result identity(HttpServletRequest request) {
        try {
            // 1、获取返回的token
            Claims token = jwt.token(request);
            // 2、判断是否携带token
            if (token == null) {
                return new Result(ResultCode.FAIL, "请重新登录后再次尝试");
            }
            // 4、获取token中的id值
            Long id = Long.valueOf(token.getId());
            // 5、进行修改
            Account account = accountService.findById(id);
            return new Result(ResultCode.SUCCESS, account.getIdentity());
        } catch (Exception e) {
            return new Result(ResultCode.SERVER_ERROR, e);
        }
    }
}
